package cn.jeeweb.modules.supervise.controller;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ff.bi.model.RptDimDataJson;
import com.ff.common.util.meta.DataFilterUtil;
import com.ff.common.util.meta.ReflectionUtil;
import com.ff.common.util.validate.ValidatorUtil;
import com.ff.common.web.json.BaseReqJson;
import com.ff.common.web.json.BaseRspJson;

import cn.jeeweb.core.common.service.ICommonService;
import cn.jeeweb.core.query.data.Condition.Filter;
import cn.jeeweb.core.query.data.QueryUtil;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresPathPermission;
import cn.jeeweb.modules.monitor.entity.McMonitorOrg;
import cn.jeeweb.modules.monitor.entity.McMonitorSensor;
import cn.jeeweb.modules.monitor.service.IMcMonitorOrgService;
import cn.jeeweb.modules.monitor.service.IMcMonitorSensorService;
import cn.jeeweb.modules.monitor.service.IMcProItemAlarmService;
import cn.jeeweb.modules.supervise.entity.McMonitorResultStatistics;
import cn.jeeweb.modules.supervise.entity.McProject;
import cn.jeeweb.modules.supervise.service.IMcProjectService;
import cn.jeeweb.modules.sys.entity.Dict;
import cn.jeeweb.modules.sys.utils.DictUtils;
import cn.jeeweb.modules.sys.utils.UserUtils;

@Controller
@RequestMapping("${admin.url.prefix}/supervise/mcprojectstatistics")
@RequiresPathPermission("supervise:mcprojectstatistics")
public class McProjectStatisticsController extends McProjectBaseController<McMonitorResultStatistics, String> {
 
	protected Logger log = Logger.getLogger(getClass());
	
	@Autowired IMcProItemAlarmService alarmService;
	@Autowired IMcProjectService projectService;
	
	@Autowired IMcMonitorSensorService sensorService;
	@Autowired IMcMonitorOrgService orgService;
	
	@RequestMapping("/by")
	@ResponseBody
	public BaseRspJson<RptDimDataJson> LoadStaus(@RequestBody BaseReqJson request){
		// TODO Auto-generated method stub
		BaseRspJson<RptDimDataJson> rsp = new BaseRspJson<RptDimDataJson>();
  		String method = this.getObj(request,String.class);

  		RptDimDataJson data = new RptDimDataJson();
		if ("status".equals(method)) {
			data = statisByStatus();
		} else if ("area".equals(method)) {
			data = statisByArea(request);
		} else if ("type".equals(method)) {
			data = statisByType();
		}
		
		rsp.setObj(data);
		
		return rsp;
	}
	
	@RequestMapping(value = "/status")
	public String byStatus(Model model, HttpServletRequest request, HttpServletResponse response) {
		
	
		return display("alarmStatus");
	}
	
	@RequestMapping(value = "/area")
	public String byArea(Model model, HttpServletRequest request, HttpServletResponse response) {
		
	
		return display("area");
	}	
	
	@RequestMapping(value = "/type")
	public String byType(Model model, HttpServletRequest request, HttpServletResponse response) {
		
	
		return display("projectType");
	}	
	
	private RptDimDataJson statisByStatus() {
		
  		EntityWrapper<McProject> entityWrapper1 = new EntityWrapper<McProject>();
 		entityWrapper1.setSqlSelect("count(1) as warnPointCount , (case  "
				+" when control_point_count>0  then '超控'"
                +" when alarm_point_count>0  then '告警'"
                +" when warn_point_count>0  then '预警'" 
                +" else   '正常'  end) as alarmStatus, "
                + "(case  "
				+" when control_point_count>0  then '超控'"
                +" when alarm_point_count>0  then '告警'"
                +" when warn_point_count>0  then '预警'" 
                +" else   '正常'  end) as code");
 		entityWrapper1.groupBy("alarmStatus");
		List<McProject> dataList = projectService.selectList(entityWrapper1);
		 
		RptDimDataJson obj = new RptDimDataJson();
		List<?> x_data =  DataFilterUtil.getFieldValueFromList(dataList, "code");
		List<?> y_data =  DataFilterUtil.getFieldValueFromList(dataList, "warnPointCount");

		obj.setX_data(x_data);
		obj.setY_data(y_data);
 
		
		return obj;
	}
	
	private RptDimDataJson statisByArea(BaseReqJson request) {
		RptDimDataJson obj = new RptDimDataJson();
		//Queryable queryable = this.GetFilterCondition(request);
		List<McProject> dataList = null;
		List<?> x_data = null;
		List<?> y_data = null;
		String provinceVal = "";
		String cityVal = "";
		String dictrictVal = "";
		List<Filter> filters = request.getFilter();
		for (Filter f : filters) {
			if("province".equals(f.getProperty())){
				provinceVal = (String) f.getValue();
			}
			if("city".equals(f.getProperty())){
				cityVal = (String) f.getValue();
			}
			if("district".equals(f.getProperty())){
				dictrictVal = (String) f.getValue();
			}
		}
		
		
  		EntityWrapper<McProject> entityWrapper1 = new EntityWrapper<McProject>();
 		
 		if (provinceVal == "" || provinceVal == null) {
 			entityWrapper1.setSqlSelect("count(1) as warnPointCount, province as code");
 			entityWrapper1.groupBy("province");
 			

 		} else if (cityVal == "" || cityVal == null) {
 			entityWrapper1.setSqlSelect("count(1) as warnPointCount, city as code");
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.groupBy("city");
 			
 		} else if (dictrictVal == "" || dictrictVal == null) {
 			entityWrapper1.setSqlSelect("count(1) as warnPointCount, district as code");
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.eq("city", cityVal);
 			entityWrapper1.groupBy("district");
 		} else {
 			entityWrapper1.setSqlSelect("count(1) as warnPointCount, district as code");
 			entityWrapper1.eq("province", provinceVal);
 			entityWrapper1.eq("city", cityVal);
 			entityWrapper1.eq("district", dictrictVal);
 		}
 		
 		dataList = projectService.selectList(entityWrapper1);
		x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dataList, "code");
		y_data =  DataFilterUtil.getFieldValueFromList(dataList, "warnPointCount");

		
		obj.setX_data(x_data);
		obj.setY_data(y_data);
 
		
		return obj;
	}
	
	private RptDimDataJson statisByType() {
		EntityWrapper<McProject> entityWrapper1 = new EntityWrapper<McProject>();
 		entityWrapper1.setSqlSelect("count(1) as warnPointCount , projectType as code");
 		entityWrapper1.groupBy("projectType");
		List<McProject> dataList = projectService.selectList(entityWrapper1);
		 
		RptDimDataJson obj = new RptDimDataJson();
		List<String> x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dataList, "code");
		List<String> x_name_data = new ArrayList<>();
		for (String s : x_data) {
			String label = DictUtils.getDictLabel(s, "XIANGMULB", s);
			x_name_data.add(label);
		}
		List<?> y_data =  DataFilterUtil.getFieldValueFromList(dataList, "warnPointCount");

		
		obj.setX_data(x_name_data);
		obj.setY_data(y_data);
 
		//RptDimDataJson data = statisByCompanyType(sensorService);
		
		//log.info(JsonConvert.ObjectToJson(data));
		
		return obj;
	}
	public RptDimDataJson statisByCompanyType(ICommonService service)
	{
		RptDimDataJson obj = new RptDimDataJson();
		
		EntityWrapper entityWrapper1 = new EntityWrapper<>();
 		entityWrapper1.setSqlSelect("count(1) as id , monitor_id as monitor_id");
 		entityWrapper1.groupBy("monitor_id");
		List<McMonitorSensor> dataList = service.selectList(entityWrapper1);
  		Map<String,McMonitorSensor> dataMap = DataFilterUtil.buildMap("monitorId", dataList);
 
  		
		Wrapper<McMonitorOrg> wrapper = new EntityWrapper<McMonitorOrg>(McMonitorOrg.class);
		List<McMonitorOrg> orgList = orgService.selectList(wrapper );
 		Map<String,List<McMonitorOrg>> orgMap = DataFilterUtil.buildMapList("companyType", orgList);
		
		List<String> y_data = new ArrayList<String>();
		
		List<Dict> dictList =  DictUtils.getDictList("company_type");
		List<String> x_data =  (List<String>) DataFilterUtil.getFieldValueFromList(dictList, "label");
		for(String e :x_data)
		{
			List<McMonitorOrg> subOrg = orgMap.get(e);
			int num = 0;
			if(!ValidatorUtil.isEmpty(subOrg))
			{
				for(McMonitorOrg org : subOrg)
				{
					Object temp = dataMap.get(org.getId());
					Object val = ReflectionUtil.getValueByFieldName(temp, "id");
					if(null != val)
					{
						num += Integer.valueOf(val.toString());
					}
					
				}
			}
 			y_data.add(String.valueOf(num));
		}
		
		obj.setX_data(x_data);
		obj.setY_data(y_data);
		return obj;
	}
	
	@RequestMapping("/sum")
	@ResponseBody
	public BaseRspJson<List<Map<String, Object>>> sum(@RequestBody BaseReqJson request) {
		// TODO Auto-generated method stub
		
 		BaseRspJson<List<Map<String, Object>>> rsp = new BaseRspJson<List<Map<String, Object>>>();
		
 		 
		Wrapper<McProject> wrapper = QueryUtil.getWrapper( this.GetFilterCondition(request), McProject.class);
		wrapper.setSqlSelect("ifnull(monitor_name,'汇总') AS monitor_name,"
				+ "count(code) as code, "
				+ "count(if(control_point_count = 0 && alarm_point_count = 0 && warn_point_count = 0,name,null)) as name,"
				+ "count(if(control_point_count != 0,control_point_count,null)) as control_point_count,"
                + "count(if(control_point_count = 0 && alarm_point_count != 0,alarm_point_count,null)) as alarm_point_count,"
                + "count(if(control_point_count = 0 && alarm_point_count = 0&&warn_point_count != 0,warn_point_count,null)) as warn_point_count");
		wrapper.groupBy("monitor_name WITH ROLLUP");
		
		wrapper.eq("monitor_org_id", UserUtils.getUser().getOrganizationIds());
		List<Map<String, Object>> obj = projectService.selectMaps(wrapper );
 		rsp.setObj(obj);
  		return rsp;
 	}
}
